package com.myacg.platform.ui.event.drag;

import java.awt.Component;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ComponentListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
/**
 * 为某个组件添加拖拽事件
 * @author Administrator
 *
 */
public class ComponentDragEvent {
	private int mousex,mousey; //记录每次鼠标按下的绝对坐标
	private int movex,movey;   //记录移动的绝对坐标
	private int mouseSelfx,mouseSelfy; //鼠标在本组件上的坐标
	private Component comp;
	private Drag  drag;  //为拖拽事件提供回掉函数
	private MouseAdapter mouse;
	private MouseMotionAdapter mouseMove;
	/**
	 * 为comp组件提供拖拽方式， 并且为Drag提供回掉函数的机会
	 * @param comp
	 * @param drag
	 */
	public ComponentDragEvent(Component comp,Drag drag){
		this(comp);
		this.drag=drag;
	}
	/**
	 * 为comp组件提供拖拽方式 
	 * @param comp
	 */
	public ComponentDragEvent(Component comp){
		this.comp=comp;
		initLinstener();
	}
	
	/**
	 * 给组件初始化监听
	 */
	private void initLinstener(){
		mouse=new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent arg0) {
				super.mousePressed(arg0);
				//System.out.println("按下");
				//arg0.getComponent().getParent().getLocation();
				mousex=arg0.getXOnScreen();
				mousey=arg0.getYOnScreen();
				
				//在此执行本组件的按下接口
				if(drag!=null)
				drag.mousePressed();
			}
			
			@Override
			public void mouseReleased(MouseEvent e) {
				super.mouseReleased(e);
				//在此执行本组件的松开接口
				if(drag!=null)
				drag.mouseReleased();
			}
		};
		
		mouseMove=new MouseMotionAdapter() {
			@Override
			public void mouseDragged(MouseEvent arg0) {
				super.mouseDragged(arg0);
				//记录拖拽的绝对坐标坐标
				movex=arg0.getXOnScreen();
				movey=arg0.getYOnScreen();
				mouseSelfx=arg0.getX();
				mouseSelfy=arg0.getY();
				//获取差额 设置comp的位置
				Point location = comp.getLocation();
				//将不满足拖拽条件的方式 交给被拖拽的控件去实现 本拖拽事件类不负责各种中断拖拽的判断条件
				if(drag == null ||  !drag.skipDrag(location.x+mouseSelfx,location.y+mouseSelfy)){
					location.x+=movex-mousex;
					location.y+=movey-mousey; 
					//重设自己的位置
					comp.setLocation(location);
					//重设基准点
					mousex=movex;
					mousey=movey; 
					//在此执行本组件的拖动接口
					if(drag!=null)
						drag.mouseDragged();
				} 
			}
	};
	}
	/**
	 * 设置拖拽事件
	 */
	public void  setDraftingEvent(){
		//为该组件添加鼠标事件
		comp.addMouseListener(this.mouse);
		//为该组件添加鼠标拖动事件
		comp.addMouseMotionListener(this.mouseMove); 
	}
	/**
	 * 移除拖拽事件
	 */
	public void  removeDraftingEvent(){
		//为该组件删除鼠标事件
		comp.removeMouseListener(this.mouse);
		//为该组件删除鼠标拖动事件
		comp.removeMouseMotionListener(this.mouseMove); 
	}
}
